#!/bin/sh
set -e
if [ -z "$SYSROOT" ]; then export SYSROOT="$(realpath "$(dirname "$0")/../sysroot")"; fi
if [ -z "$LLVMDIR" ]; then export LLVMDIR="$(realpath "$(dirname "$0")/../llvm-project")"; fi
if [ -f "$SYSROOT/bin/musl-gcc" ]; then export CC="$SYSROOT/bin/musl-gcc"; fi
if [ -f "$SYSROOT/bin/musl-clang" ]; then export CC="$SYSROOT/bin/musl-clang"; fi

rm -rf build-
mkdir build-
cd build-
export ASMFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none"
export CFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none"
export CXXFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none -fno-use-cxa-atexit"
export LDFLAGS="-no-pie"

cmake \
	-DCMAKE_ASM_COMPILER="$CC" \
	-DCMAKE_C_COMPILER="$CC" \
	-DCMAKE_CXX_COMPILER="$CC" \
	-DLLVM_TARGET_TRIPLE="x86_64-unknown-linux-gnu" \
	-DCOMPILER_RT_BUILD_CRT=OFF \
	-DCOMPILER_RT_BUILD_SANITIZERS=OFF \
	-DCOMPILER_RT_BUILD_XRAY=OFF \
	-DCOMPILER_RT_BUILD_LIBFUZZER=OFF \
	-DCOMPILER_RT_BUILD_PROFILE=OFF \
	-DCOMPILER_RT_BUILD_MEMPROF=OFF \
	-DCOMPILER_RT_BUILD_ORC=OFF \
	-DCOMPILER_RT_BUILD_GWP_ASAN=OFF \
	-DCOMPILER_RT_CAN_EXECUTE_TESTS=OFF \
	-DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON \
	-UCOMPILER_RT_BAREMETAL_BUILD \
	-DCOMPILER_RT_BAREMETAL_BUILD=ON \
	-DCOMPILER_RT_BUILTINS_ENABLE_PIC=OFF \
	-DCMAKE_INSTALL_PREFIX="$SYSROOT" \
	$LLVMDIR/compiler-rt
